package com.hqyj.springCloudAccount.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.entity.account.Role;
import com.hqyj.entity.common.ResultEntity;
import com.hqyj.entity.common.SearchBean;
import com.hqyj.springCloudAccount.dao.RoleDao;
import com.hqyj.springCloudAccount.dao.RoleResourceDao;
import com.hqyj.springCloudAccount.dao.UserRoleDao;
import com.hqyj.springCloudAccount.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleResourceDao roleResourceDao;
    @Override
    public ResultEntity<Role> addRole(Role role) {
        role.setCreateDate(LocalDateTime.now());
        roleDao.addRole(role);
        return new ResultEntity<Role>(ResultEntity.ResultStatus.SUCCESS.status,"添加成功！",role);
    }

    @Override
    public ResultEntity<Role> updateRoleByRole(Role role) {
        roleDao.updateRoleByRole(role);
        return new ResultEntity<Role>(ResultEntity.ResultStatus.SUCCESS.status,"修改成功！",role);
    }

    @Override
    public ResultEntity<Role> deleteRoleById(int id) {
        roleDao.deleteRoleById(id);
        userRoleDao.deleteUserRoleByRoleId(id);
        roleResourceDao.deleteRoleResourceByRoleId(id);
        return new ResultEntity<Role>(ResultEntity.ResultStatus.SUCCESS.status,"删除成功！");
    }

    @Override
    public Role selectRoleById(int id) {
        return roleDao.selectRoleById(id);
    }

    @Override
    public List<Role> selectAllRole() {
//        return roleDao.selectAllRole();
        return Optional.ofNullable(roleDao.selectAllRole()).orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<Role> getRolesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(), searchBean.getPageSize());
        return new PageInfo<Role>(Optional
                .ofNullable(roleDao.getRolesBySearchBean(searchBean))
                .orElse(Collections.emptyList()));
    }

    @Override
    public List<Role> getRolesByUserId(int userId) {
        return roleDao.getRolesByUserId(userId);
    }
}
